package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author fengx
 * 新疆一体化答题 按课程答题
 * 管理学基础
 * 基础汉语(1)
 * 个人与团队管理
 * 公共政策概论
 * 社会调查研究与方法
 */
@Slf4j
public class DoXJAnswerHomeworktmpppp {

    final static Object lock = new Object();


    public static void main(String[] args) throws Exception {

        Thread.sleep(1000*60*60*3);
        //是否提交答案
        boolean commit = true;
        // 视频的数量 和作业数量是否相等 （是否有导论），相等就是true
        //并发开启的浏览器数量
        int sync = 6;
        //驱动路径
        String driverPath = "c:\\ynouAutoStudy\\chromedriver.exe";
        //初始化日志配置
        //初始化日志配置
        Constant.initLog();




        //预加载所有用户信息
        InputStream inputStream3 = new FileInputStream("E:\\alluser.txt");
        List<String> allUsers = IOUtils.readLines(inputStream3, "utf-8");
        Map<String, String> usernameAndPwd = Maps.newHashMap();

        for (String user : allUsers) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1];
            if (pwd.length() > 14) {
                if (pwd.contains("X")) {
                    pwd = userCode.substring(11, 17);
                } else {
                    pwd = userCode.substring(12);
                }
            }
            usernameAndPwd.put(userCode.toUpperCase(Locale.ROOT), pwd);
            if(Strings.isNullOrEmpty(pwd)||pwd.length()<6){
                System.err.println("????????:"+userCode);
            }
        }

        // Thread.sleep(20000000);


        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");
        Map<String, String> mapTmp = Maps.newHashMap();
        for (String keyValues : allKeyValues) {
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1, v1);
        }

        //加载所有课程配置
        List<CourseInfo> courseList = Lists.newArrayList();
     //   for (File file : new File("E:\\XjStudentCourseInfoTmp\\names\\tmp").listFiles()) {
        for (File file : new File("E:\\XjStudentCourseInfoTmp\\names").listFiles()) {
            if(file.isDirectory()){
                continue;
            }
            String fileName = file.getName();
            String code = fileName.substring(0, fileName.length() - 5);
            CourseInfo courseInfo = new CourseInfo();
            courseInfo.setOpenCourseId(Integer.parseInt(code));
            courseInfo.setSubjectName(mapTmp.get(code));
            courseList.add(courseInfo);
            //Constant.COURSE_QUEUE.addLast(new CourseInfo(Integer.parseInt(code), mapTmp.get(code)));
        }
        Collections.sort(courseList);

        //加载每个课程答案
        for (CourseInfo info : courseList) {
            //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
          try {
              System.err.println(info);
              String subjectName = info.getSubjectName();
              subjectName = subjectName.trim();
              int  openCourseId = info.getOpenCourseId();
              InputStream inputStream1 = new FileInputStream("D:\\新疆一体化平时作业\\" + openCourseId + "\\" + subjectName + "（平时作业）.json");
              String answerStr = IOUtils.toString(inputStream1, StandardCharsets.UTF_8);
              List<AnswerObject> listAnswerObject = JSONObject.parseArray(answerStr, AnswerObject.class);
              Map<String, AnswerObject> answerMap = Maps.newHashMap();
              for (AnswerObject answerObject : listAnswerObject) {
                  answerMap.put(DealJsonString.delHTMLTag(Util.dealContent(answerObject.getQuestionTitle())), answerObject);
              }
              info.setAnswerMap(answerMap);
          }catch (FileNotFoundException e ){
              System.out.println(info.getSubjectName());
              e.printStackTrace();
          }
        }



        //加载用户答题参数
        LinkedBlockingDeque<CourseInfo> userCourseQueue = new LinkedBlockingDeque<>();
        for (CourseInfo courseInfo : courseList) {
            InputStream inputStream4 = new FileInputStream("E:\\XjStudentCourseInfoTmp\\names\\" + courseInfo.getOpenCourseId() + ".json");
            String userStr = IOUtils.toString(inputStream4, StandardCharsets.UTF_8);
            // 当前这门课程所有的
            List<String> users = JSONObject.parseArray(userStr, String.class);
            for (String s : users) {
                int openCourseId = courseInfo.getOpenCourseId();
                String pwd = usernameAndPwd.get(s.toUpperCase(Locale.ROOT));
                CourseInfo courseInfo1 = new CourseInfo();
                courseInfo1.setAnswerMap(courseInfo.getAnswerMap());
//                // 30913 管理学基础 没有作业
//                if(openCourseId==30913){
//                    continue;
//                }
                courseInfo1.setOpenCourseId(courseInfo.getOpenCourseId());
                courseInfo1.setSubjectName(courseInfo.getSubjectName());
                courseInfo1.setPwd(pwd);
                courseInfo1.setUser(s);
                if(courseInfo.getOpenCourseId()==33615){
                    System.out.println("content:"+JSON.toJSONString(courseInfo1));
                }
                userCourseQueue.addLast(courseInfo1);
            }
        }




//        log.info("本次加载课程：{} ", mapByOpenCourseId.size());
//        for(Integer key:courseMap.keySet()){
//            log.info("本次加载课程ID：{} 用户数：{} ", key,courseMap.get(key).size());
//        }

     //   log.info("本次程序将加载 {} 个线程同时运行", group.size());
        //把信息读出来 写个info log

      //  Thread.sleep(2000000);
        for (int i = 1; i <= sync; i++) {
            Thread answerThread = new DoXJAnswerHomeworkTask(driverPath,userCourseQueue);
            //log.info("加载课程ID：{} 名称：{} ", openCourseId,subjectName);
            answerThread.setName( "答题线程--" + i);
            answerThread.start();
        }

    }

}
